from rest_framework import serializers
from users.models import User
import re


class UserSerializer(serializers.ModelSerializer):

    token = serializers.CharField(label='token', read_only=True)

    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'password', 'token', 'avatar')

        extra_kwargs = {
            'username': {
                'max_length': 20,
                'min_length': 5
            },
            'password': {
                'max_length': 16,
                'min_length': 6,
                'write_only': True

            },
        }

    def create(self, validated_data):
        # 保存用户数据并对密码加密
        user = User.objects.create_user(**validated_data)
        return user

    def validate(self, attrs):
        username = attrs['username']
        mobile = attrs['mobile']
        password = attrs['password']

        # # username检验
        if not re.match(r'[a-zA-Z0-9_-]{5,20}$', username):
            raise serializers.ValidationError('请输入5-20位数用户名')

        # mobile检验
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            raise serializers.ValidationError('请输入11位数字手机号')

        # password检验
        if not re.match(r'[a-zA-Z0-9]{6,16}$', password):
            raise serializers.ValidationError('请输入6-16位数密码')

        return attrs
